/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
 */

import { exit } from '../base/boot/hooks/exit.js';
import { CUR_HVIGOR_VERSION } from '../cli/wrapper/wrapper-const.js';

const COMMAND_DESCRIPTION = require('../base/command/constants.json');
// command中选项参数信息定义
type Option = {
  name: string;
  flag: string;
  description: string;
  back: string;
  flagPair: boolean;
  deprecated: boolean;
  recommendedFlags: string;
};

// command中after信息(即如Examples)定义
type After = {
  position: string;
  text: string;
};

function padString(str: string, length = 34, padChar = ' ') {
  return str.padEnd(length, padChar);
}

export const GlobalExecute = {
  version: (args: string) => {
    if (args.includes('--version') || args.includes('-v')) {
      console.log(CUR_HVIGOR_VERSION);
      exit(0);
    } else {
      console.log('hvigor', '\x1b[32mCLI version:', CUR_HVIGOR_VERSION, '\x1b[0m');
      console.log('hvigor', '\x1b[32mLocal version:', CUR_HVIGOR_VERSION || 'Unknown', '\x1b[0m');
      exit(0);
    }
  },
  help: () => {
    // 打印usage
    console.log('Usage: ', COMMAND_DESCRIPTION.options.usage.flag, COMMAND_DESCRIPTION.options.usage.description, '\n');

    // 打印Options 包含version、basicOptions、otherOptions
    console.group('Options: ');
    const version: Option = COMMAND_DESCRIPTION.options.version;

    const basicOptions: Option[] = COMMAND_DESCRIPTION.options.basicOptions;
    console.log(padString(version.flag), version.description);
    basicOptions.forEach((item) => {
      console.log(padString(item.flag), item.description);
    });

    const otherOptions: Option[] = COMMAND_DESCRIPTION.options.otherOptions;
    otherOptions.forEach((item) => {
      if (item.flagPair) {
        console.log(padString('--'.concat(item.flag)), 'Enables '.concat(item.description));
        console.log(padString('--no-'.concat(item.flag)), 'Disables '.concat(item.description));
      } else {
        console.log(padString(item.flag), item.description);
      }
    });

    // 拼接help信息
    const help: Option = COMMAND_DESCRIPTION.help;
    console.log(padString(help.flag), help.description, '\n');
    console.groupEnd();

    // 打印command,即hvigorw 任务列表
    console.group('Commands: ');
    const commands: Option[] = COMMAND_DESCRIPTION.command;
    commands.forEach((item) => {
      console.log(padString(item.name), item.description);
    });
    console.groupEnd();

    // 打印Examples信息
    const afters: After[] = COMMAND_DESCRIPTION.after;
    afters?.forEach((item) => {
      console.log(item.text);
    });
    exit(0);
  },
};

export const globalVersionCommands = ['-v', '--version', 'version'];
export const globalHelpCommands = ['-h', '--help'];
